<template>
  <xr-create
    :loading="loading"
    :title="title"
    :show-confirm="config.showConfirm"
    :show-cancel="config.showCancel"
    @close="hidenView"
    @save="saveClick('save')">
    <template
      v-if="!config.getFields"
      slot="footer">
      <el-button
        @click="saveClick('draft')">保存为草稿</el-button>
    </template>
    <!-- 基本信息 -->
    <create-sections :title="$t('oa.examine.6f8a9584e530886490bb62cd3ee5ca8c')">
      <el-form
        ref="crmForm"
        :model="fieldForm"
        :rules="fieldRules"
        :validate-on-rule-change="false"
        class="wk-form"
        label-position="top">
        <wk-form-items
          v-for="(children, index) in fieldList"
          :key="index"
          :field-from="fieldForm"
          :field-list="children"
          :ignore-fields="['money','handled']"
          @change="formChange"
        >
          <template slot-scope="{ data }">
            <xh-expenses
              v-if="data && data.formType == 'examine_cause'"
              :value="fieldForm[data.field]"
              :props="specialFieldProps[data.formType]"
              @value-change="otherChange($event, data)"
            />
            <xh-leaves
              v-if="data && data.formType == 'business_cause'"
              :value="fieldForm[data.field]"
              :props="specialFieldProps[data.formType]"
              @value-change="otherChange($event, data)"
            />
            <div v-if="data && data.field == 'handled'">
              <wk-user-dialog-select
                ref="wkUserDialogSelect"
                v-model="fieldForm[data.field]"
                :disabled="data.disabled"
                :radio="data.radio"
                style="width: 100%;"
                @change="userChange" />
              <el-button
                v-if="!data.disabled"
                type="primary-text"
                @click="addUser"
              >+添加经办人</el-button>
            </div>
            <div v-if="data.field == 'money'" style="position: relative;line-height: normal;">
              <el-input
                v-model="fieldForm[data.field]"
                :disabled="data.disabled"
                :maxlength="804"
                @input="formChange(data)">
                <template slot="append">
                  <el-button
                    v-if="userInfo.loginType != 3"
                    type="text"
                    class="wk-premium-info-btn"
                    style="padding-right: 5px;">
                    <i
                      class="wk wk-icon-lightning-solid wk-premium-info-icon" />
                    <span class="wk-premium-info-label" data-type="Bill">
                      {{ $t('oa.examine.c4a03105daab6fdbc1cb78ad5699a010') }}
                    </span>
                  </el-button>
                </template>
              </el-input>
            </div>
          </template>
        </wk-form-items>
      </el-form>
    </create-sections>

    <!-- 图片附件 -->
    <div
      v-if="!config.getFields"
      class="img-accessory">
      <div class="img-box">
        <el-upload
          ref="imageUpload"
          :action="crmFileSaveUrl"
          :headers="httpHeader"
          :data="{type: 'img', batchId: batchId}"
          :on-preview="handleFilePreview"
          :before-remove="beforeRemove"
          :on-success="imgFileUploadSuccess"
          :file-list="imgFileList"
          name="file"
          multiple
          accept="image/*"
          list-type="picture-card">
          <el-button class="add-img" type="text">
            {{ $t('oa.examine.aca17864f451b3d0eefe6ff9fde585e2') }}
          </el-button>
          <i class="el-icon-plus" />
        </el-upload>
      </div>
      <div class="add-accessory">
        <!-- <el-upload
            ref="fileUpload"
            :action="crmFileSaveUrl"
            :headers="httpHeader"
            :data="{type: 'file', batchId: batchId}"
            :on-preview="handleFilePreview"
            :before-remove="handleFileRemove"
            :on-success="fileUploadSuccess"
            :file-list="fileList"
            name="file"
            multiple
            accept="*.*">
            <el-button type="text" style="padding: 0;">添加附件</el-button>
          </el-upload> -->
        <file-cell
          :file-list="fileList"
          :show-time="false"
          show-delete
          @delete="fileDelete(arguments[0],arguments[1], data)" />
        <el-upload
          :http-request="httpRequest"
          class="upload-file"
          action="https://jsonplaceholder.typicode.com/posts/"
          multiple
          list-type="picture">
          <span class="add-btn">
            <i class="wk wk-l-plus" />
            <span class="label">
              {{ $t('oa.examine.5821bb2682967c37ea3d9cab85e2f2b3') }}
            </span>
          </span>
        </el-upload>
      </div>
    </div>
    <!-- 相关信息 -->
    <div
      v-if="!config.getFields"
      style="padding-right: 12px;">
      <related-business
        :show-foot="true"
        :selected-infos="relatedBusinessInfo"
        @checkInfos="relativeValueChange" />
    </div>
    <!-- 审核信息 -->
    <!-- <create-sections
      v-if="wkFlowList"
      :title="$t('oa.examine.4e493bfe644e1fd50a043857ed113571')">
      <template slot="header">
        <el-tooltip
          v-if="flowRemarks"
          :content="flowRemarks"
          effect="dark"
          placement="top">
          <i class="wk wk-help wk-help-tips" style="margin-left: 8px;" />
        </el-tooltip>
      </template>
      <wk-approval-flow-apply
        :data="wkFlowList"
        :approver-edit-auth="approverEditAuth"
        :carbon-copy-edit-auth="carbonCopyEditAuth"
        :is-edit="action.hasOwnProperty('examineInfo') && action.examineInfo.examineStatus == 2"
        :examine-advanced-setting="examineAdvancedSetting"
        style="padding: 15px;"
      />
    </create-sections> -->
    <create-sections
      v-if="wkFlowList"
      title="审核信息">
      <template slot="header">
        <el-tooltip
          v-if="flowRemarks"
          :content="flowRemarks"
          effect="dark"
          placement="top">
          <i class="wk wk-help wk-help-tips" style="margin-left: 8px;" />
        </el-tooltip>
      </template>
      <wk-af-new-apply
        ref="afNewApply"
        :data="wkFlowList"
        :approver-edit-auth="approverEditAuth"
        :detail="examineAdvancedSetting"
        style="padding: 15px;" />
    </create-sections>

    <template slot="footer-left">
      <slot name="footer" />
    </template>
  </xr-create>
</template>

<script type="text/javascript">
import { filedGetFieldAPI } from '@/api/crm/common'
import { oaExamineGetFieldAPI } from '@/api/oa/examine'
import { crmFileDeleteAPI, crmFileSaveUrl } from '@/api/common'
import {
  oaExamineSaveAndUpdateAPI,
  oaExamineSaveDraftAPI
} from '@/api/oa/examine'
import { examinesDraftFiledNameAPI } from '@/api/examine'

import XrCreate from '@/components/XrCreate'
import CreateSections from '@/components/CreateSections'
import XhExpenses from './XhExpenses' // 报销事项
import XhLeaves from './XhLeaves' // 出差事项
import WkUserDialogSelect from '@/components/NewCom/WkUserDialogSelect'
// import RelatedBusiness from './RelatedBusiness'
import RelatedBusiness from '@/components/RelatedBusiness'
import FileCell from '@/components/FileCell'

// import WkApprovalFlowApply from '@/components/Examine/WkApprovalFlowApply'
import WkApprovalFlowApplyMixin from '@/components/Examine/mixins/WkApprovalFlowApply'
import WkAfNewApply from '@/components/Examine/WkAfNewApply'
import WkFormItems from '@/components/NewCom/WkForm/WkFormItems'

import { isEmpty, isObject, isArray } from '@/utils/types'
import CustomFieldsMixin from '@/mixins/CustomFields'
import CrmCreateMixin from '@/mixins/CrmCreateMixin'
import axios from '@/utils/request'
import { mapGetters } from 'vuex'
import moment from 'moment'

import {
  guid,
  objDeepCopy,
  getImageData
} from '@/utils'

export default {
  name: 'ExamineCreateView', // 所有新建效果的view
  components: {
    XrCreate,
    CreateSections,
    XhExpenses,
    XhLeaves,
    RelatedBusiness,
    // WkApprovalFlowApply,
    WkAfNewApply,
    WkFormItems,
    FileCell,
    WkUserDialogSelect
  },
  filters: {},
  mixins: [CustomFieldsMixin, WkApprovalFlowApplyMixin, CrmCreateMixin],
  props: {
    // 类型ID
    categoryId: {
      type: [String, Number],
      default: ''
    },
    // 辅助类型字段
    type: [String, Number],
    // 类型名称
    categoryTitle: {
      type: String,
      default: ''
    },
    /**
     * save:添加、update:编辑(action_id)、read:详情、index:列表
     * relative: 相关 添加
     */
    action: {
      type: Object,
      default: () => {
        return {
          type: 'save',
          id: ''
        }
      }
    },
    examineType: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // 标题展示名称
      loading: false,
      // 自定义字段验证规则
      baseFields: [],
      fieldList: [],
      fieldForm: {},
      fieldRules: {},
      batchId: guid(),
      // 图片附件
      imgFileList: [],
      fileList: [],
      // 审批信息
      flowRemarks: '',
      wkFlowList: null, // 有值有审批流
      relatedBusinessInfo: {}, // 相关信息信息
      approverEditAuth: false, // 固定审批人是否可修改
      carbonCopyEditAuth: false, // 固定抄送人是否可修改
      specialFieldProps: {} // 以formType当做key  值为  table 和 field
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
    title() {
      if (this.config.title) return this.config.title
      return this.getTitle()
    },
    crmFileSaveUrl() {
      return crmFileSaveUrl
    },
    httpHeader() {
      return {
        'Admin-Token': axios.defaults.headers.common['Admin-Token']
      }
    }
  },
  watch: {},
  mounted() {
    // 获取title展示名称
    document.body.appendChild(this.$el)
    if (this.config.getFields) {
      this.getCustomField()
    } else {
      this.getField()
      if (this.action.type == 'update') {
        this.batchId = this.action.data.batchId
      }
    }
  },
  destroyed() {
    // remove DOM node after destroy
    if (this.$el && this.$el.parentNode) {
      this.$el.parentNode.removeChild(this.$el)
    }
  },
  methods: {
    /**
     * 相关信息的值更新
     */
    relativeValueChange(data, value) {
      this.relatedBusinessInfo = value
    },

    /**
     * change
     */
    formChange(field, index, value, valueList) {
      // 审批流逻辑
      // this.debouncedGetWkFlowList(field.field, this.fieldForm)

      if ([
        'select',
        'checkbox'
      ].includes(field.formType) &&
          field.remark === 'options_type' &&
          field.optionsData) {
        const { fieldForm, fieldRules } = this.getFormContentByOptionsChange(this.fieldList, this.fieldForm)
        this.fieldForm = fieldForm
        this.fieldRules = fieldRules
      }
    },

    /**
     * change
     */
    otherChange(data, field) {
      // 出差事项
      // 审批授权字段明细修改不覆盖总值
      if (!this.config.getFields && data.value.update) {
        if (field.formType == 'business_cause') {
          this.$set(this.fieldForm, 'duration', data.value.duration)
        } else if (field.formType == 'examine_cause') {
          this.$set(this.fieldForm, 'money', data.value.money)
        }
      }
      this.$set(this.fieldForm, field.field, data.value)
    },

    /**
     * 获取自定义字段
     */
    getField() {
      this.loading = true
      // 获取自定义字段的更新时间
      var params = {}
      params.label = 10
      params.id = this.categoryId

      // 进行编辑操作
      if (this.action.type == 'update') {
        params.examineId = this.action.id
        params.isDetail = 2 // 1详情 2 编辑
      }

      const request = {
        update: oaExamineGetFieldAPI,
        save: filedGetFieldAPI
      }[this.action.type]
      request(params)
        .then(res => {
          this.getcrmRulesAndModel(res.data)
          if (this.action.type == 'update') {
            this.getUpdateOtherInfo()
          }

          // 审核信息
          const examineParams = {
            label: 0,
            examineId: this.categoryId
          }

          // 编辑回填审批流
          if (this.action.hasOwnProperty('examineInfo')) {
            const { examineStatus, recordId } = this.action.examineInfo

            if (examineStatus == 2) {
              examineParams.recordId = recordId
            }
          }

          this.initWkFlowData({
            params: examineParams,
            fieldForm: this.fieldForm // 该对象没有需要适配
          }, res => {
            const list = res.list
            list.forEach(item => {
              if (item.rangeType === 2 || item.rangeType == 3) {
                item.finalUserList = objDeepCopy(item.userList)
                item.userList = []
              }
            })
            this.wkFlowList = list

            if (this.action.type == 'update' && this.examineType == 'draft') {
              this.getDraftFlow()
            }
            this.flowRemarks = res.resData ? res.resData.remarks : ''

            // 固定审批人/抄送人修改权限
            const modifyPermissionType = this.examineAdvancedSetting?.modifyPermissionType
            if (isEmpty(modifyPermissionType)) {
              this.approverEditAuth = true
              this.carbonCopyEditAuth = true
            } else {
              this.approverEditAuth = !modifyPermissionType.includes(1)
              this.carbonCopyEditAuth = !modifyPermissionType.includes(2)
            }
          })

          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },

    /**
     * @description: 自定义获取
     * @return {*}
     */
    getCustomField() {
      this.loading = true
      this.config.getFields().then(fields => {
        console.log('fields---', fields)

        // 在该响应下能保证data有值
        if (this.action.type == 'update') {
          this.batchId = this.action.data.batchId
        }

        const list = this.convertToTwoFields(fields)

        const baseFields = []
        const fieldList = []
        const fieldRules = {}
        const fieldForm = {}

        list.forEach(children => {
          const fields = []
          children.forEach(item => {
            const temp = this.getFormItemDefaultProperty(item)
            temp.show = true

            const canEdit = this.getItemIsCanEdit(item, this.action.type)
            // 是否可编辑
            temp.disabled = !canEdit

            // 特殊字段验证规则
            if (item.isNull == 1) {
              if (item.formType == 'business_cause') {
                this.$set(this.specialFieldProps, item.formType, this.getSpecialFieldProps(item))
                const causeValidateFun = (rule, value, callback) => {
                  if (!value.list) {
                    callback(new Error('请完善明细'))
                  } else {
                    var hasError = false
                    for (let vIndex = 0; vIndex < value.list.length; vIndex++) {
                      const vItem = value.list[vIndex]
                      const defaultKeys = [
                        'startAddress',
                        'endAddress',
                        'startTime',
                        'endTime',
                        'duration'
                      ]

                      const keys = (item.fieldExtendList?.map(obj => obj.fieldName) || []).filter(fieldKey => defaultKeys.includes(fieldKey))
                      for (let keyIndex = 0; keyIndex < keys.length; keyIndex++) {
                        const key = keys[keyIndex]
                        if (key == 'duration') {
                          if (vItem.duration <= 0) {
                            hasError = true
                            callback(new Error(`行程明细（${vIndex + 1}）时长应大于0`))
                            break
                          }
                        } else if (isEmpty(vItem[key])) {
                          hasError = true
                          callback(new Error('请完善明细'))
                          break
                        }
                      }
                    }
                    if (!hasError) {
                      callback()
                    }
                  }
                }
                fieldRules[temp.field] = [{
                  validator: causeValidateFun,
                  trigger: []
                }, {
                  required: true,
                  message: '请完善明细',
                  trigger: ['blur', 'change']
                }]
              } else if (item.formType == 'examine_cause') {
                this.$set(this.specialFieldProps, item.formType, this.getSpecialFieldProps(item))
                const examineValidateFun = (rule, value, callback) => {
                  if (!value.list) {
                    callback(new Error('请完善明细'))
                  } else {
                    var hasError = false
                    for (let vIndex = 0; vIndex < value.list.length; vIndex++) {
                      const vItem = value.list[vIndex]
                      const defaultKeys = [
                        'startAddress',
                        'endAddress',
                        'startTime',
                        'endTime',
                        'traffic',
                        'stay',
                        'diet',
                        'other'
                      ]

                      const keys = (item.fieldExtendList?.map(obj => obj.fieldName) || []).filter(fieldKey => defaultKeys.includes(fieldKey))
                      console.log('item.fieldExtendList---', item.fieldExtendList, keys)
                      for (let keyIndex = 0; keyIndex < keys.length; keyIndex++) {
                        const key = keys[keyIndex]
                        if (isEmpty(vItem[key])) {
                          hasError = true
                          callback(new Error('请完善明细'))
                          break
                        }
                      }

                      if (vItem.money <= 0) {
                        hasError = true
                        callback(new Error(`费用明细（${vIndex + 1}）合计应大于0`))
                        break
                      }
                    }
                    if (!hasError) {
                      callback()
                    }
                  }
                }
                fieldRules[temp.field] = [{
                  validator: examineValidateFun,
                  trigger: []
                }, {
                  required: true,
                  message: '请完善明细',
                  trigger: ['blur', 'change']
                }]
              } else if ((item.fieldName == 'duration' && this.type == 3) ||
          (item.fieldName == 'money' && this.type == 5)) {
                fieldRules[temp.field] = [{
                  required: true,
                  message: '请完善明细',
                  trigger: ['blur', 'change']
                }]
              }
            }

            // disabled
            if (
            // 出差审批 差旅报销
              (item.fieldName == 'duration' && this.type == 3) ||
          (item.fieldName == 'money' && this.type == 5)
            ) {
              temp.disabled = true
            }

            // 特殊字段允许多选
            this.getItemRadio(item, temp)

            // 获取默认值
            if (item.formType == 'examine_cause' ||
          item.formType == 'business_cause') {
              if (this.action.type == 'update') {
                const itemValue = item.value || []
                const list = itemValue.map(element => {
                  if (element.img) {
                    element.imgList = objDeepCopy(element.img || [])
                  } else {
                    element.imgList = []
                  }
                  return element
                })
                fieldForm[temp.field] = { list: list } // 编辑的值 在value字段
              } else {
                fieldForm[temp.field] = {} // 加入默认值 可能编辑的时候需要调整
              }
            } else {
              if (temp.show) {
                // 这里都是类似编辑的逻辑，不需要默认值的赋值
                // if (item.fieldName == 'handled') {
                //   item.defaultValue = [this.userInfo.userId]
                //   if (this.action.type == 'update') {
                //     if (isObject(temp.value)) {
                //       item.value = [temp.value.userId]
                //     } else if (isArray(temp.value)) {
                //       item.value = temp.value.map(item => item.userId)
                //     }
                //   }
                // }
                // if (item.fieldName == 'submitDeptId') {
                //   item.defaultValue = this.userInfo.deptId
                // }
                if (item.fieldName == 'telephone') {
                  // item.defaultValue = this.userInfo.mobile
                  if (this.action.type == 'update') {
                    item.value = temp.value
                  }
                }
                if (item.fieldName == 'submitTime') {
                  // item.defaultValue = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
                  if (this.action.type == 'update') {
                    item.value = temp.value
                  }
                }
                fieldForm[temp.field] = this.getItemValue(item, this.action.data, this.action.type)
              }
            }
            fields.push(temp)
            baseFields.push(item)
          })
          fieldList.push(fields)
        })
        this.baseFields = baseFields
        this.fieldList = fieldList

        // fieldRules 额外的自定义规则
        this.fieldRules = fieldRules
        const result = this.getFormContentByOptionsChange(fieldList, fieldForm)
        this.fieldForm = result.fieldForm
        this.fieldRules = result.fieldRules

        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },

    /**
     * @description: 获取特殊字段配置
     * @param {*} field
     * @return {*}
     */
    getSpecialFieldProps(dataItem) {
      const props = {
        table: {},
        field: {},
        showSubTotal: !this.config.getFields
      }
      const binaryStr = dataItem.tableLevel.toString(2).padStart(3, '0')
      // Boolean(Number(binaryStr.charAt(0))) // 行添加
      // Boolean(Number(binaryStr.charAt(1))) // 行编辑
      // Boolean(Number(binaryStr.charAt(2))) // 行删除
      props.table.addDisabled = !Number(binaryStr.charAt(0))
      props.table.delDisabled = !Number(binaryStr.charAt(2))
      dataItem.fieldExtendList.forEach(item => {
        if (item.authLevel == 2 || item.authLevel == 3) {
          // dataItem 父层不能编辑，里层也不能编辑
          props.field[item.fieldName] = item.authLevel == 2 || dataItem.authLevel != 3
        }
      })
      return props
    },

    /**
     * 草稿获取审批流
     */
    getDraftFlow() {
      examinesDraftFiledNameAPI({ examineId: this.action.id })
        .then(res => {
          const data = JSON.parse(res.data)
          this.wkFlowList = data.examineFlowFinalBOList
        })
    },

    /**
     * 更新图片附件相关信息信息
     */
    getUpdateOtherInfo() {
      this.imgFileList = objDeepCopy(this.action.data.img || [])

      for (let index = 0; index < this.imgFileList.length; index++) {
        this.setImageList(this.imgFileList[index], index)
      }

      this.fileList = objDeepCopy(this.action.data.file || [])

      this.relatedBusinessInfo = {
        contacts: (this.action.data.contactsList || []).map(item => {
          if (item.id) {
            item.contactsId = item.id
          }
          return item
        }),
        customer: (this.action.data.customerList || []).map(item => {
          if (item.id) {
            item.customerId = item.id
          }
          return item
        }),
        business: (this.action.data.businessList || []).map(item => {
          if (item.id) {
            item.businessId = item.id
          }
          return item
        }),
        contract: (this.action.data.contractList || []).map(item => {
          if (item.id) {
            item.contractId = item.id
          }
          return item
        }),
        receivables: (this.action.data.receivablesList || []).map(item => {
          if (item.id) {
            item.receivablesId = item.id
          }
          return item
        })
      } // 相关信息信息
    },

    /**
     * 获取图片内容
     */
    setImageList(item, index) {
      getImageData(item.url).then((data) => {
        item.url = data.src
        this.imgFileList.splice(index, 1, item)
      }).catch(() => {})
    },

    /**
     * 根据自定义字段获取自定义字段规则
     */
    getcrmRulesAndModel(list) {
      const baseFields = []
      const fieldList = []
      const fieldRules = {}
      const fieldForm = {}

      list.forEach(children => {
        const fields = []
        children.forEach(item => {
          const temp = this.getFormItemDefaultProperty(item)
          temp.show = true

          // 特殊字段验证规则
          if (item.isNull == 1) {
            if (item.formType == 'business_cause') {
              const causeValidateFun = (rule, value, callback) => {
                if (!value.list) {
                  callback(new Error(this.$t('oa.examine.977bac9a6ceba81a0c341b8e63b0f43b')))
                } else {
                  var hasError = false
                  for (let index = 0; index < value.list.length; index++) {
                    const item = value.list[index]
                    const keys = [
                      'startAddress',
                      'endAddress',
                      'startTime',
                      'endTime',
                      'duration'
                    ]
                    for (let keyIndex = 0; keyIndex < keys.length; keyIndex++) {
                      const key = keys[keyIndex]
                      if (key == 'duration') {
                        if (item.duration <= 0) {
                          hasError = true
                          callback(new Error(this.$t('oa.examine.38a900079e2b18f28ce08312570f4d31', { 1: index + 1 })))
                          break
                        }
                      } else if (isEmpty(item[key])) {
                        hasError = true
                        callback(new Error(this.$t('oa.examine.33c98264a4f5d2abc49ef7e562b13b45')))
                        break
                      }
                    }
                  }
                  if (!hasError) {
                    callback()
                  }
                }
              }
              fieldRules[temp.field] = [{
                validator: causeValidateFun,
                trigger: []
              }, {
                required: true,
                message: this.$t('oa.examine.ce09a5054f141cc841c9b9ccc5d68f97'),
                trigger: ['blur', 'change']
              }]
            } else if (item.formType == 'examine_cause') {
              const examineValidateFun = (rule, value, callback) => {
                if (!value.list) {
                  callback(new Error(this.$t('oa.examine.c010f309de10f05d4ff49c427c05de58')))
                } else {
                  var hasError = false
                  for (let index = 0; index < value.list.length; index++) {
                    const item = value.list[index]
                    const keys = [
                      'startAddress',
                      'endAddress',
                      'startTime',
                      'endTime',
                      'traffic',
                      'stay',
                      'diet',
                      'other'
                    ]
                    for (let keyIndex = 0; keyIndex < keys.length; keyIndex++) {
                      const key = keys[keyIndex]
                      if (isEmpty(item[key])) {
                        hasError = true
                        callback(new Error(this.$t('oa.examine.b61a7a061e9a04036d22a3b77ebec859')))
                        break
                      }
                    }

                    if (item.money <= 0) {
                      hasError = true
                      callback(new Error(this.$t('oa.examine.c8392a141e46ae75b6bea7b87ccb1664', { 1: index + 1 })))
                      break
                    }
                  }
                  if (!hasError) {
                    callback()
                  }
                }
              }
              fieldRules[temp.field] = [{
                validator: examineValidateFun,
                trigger: []
              }, {
                required: true,
                message: this.$t('oa.examine.2f22f9b6f1b102d3985fe9098556f695'),
                trigger: ['blur', 'change']
              }]
            } else if ((item.fieldName == 'duration' && this.type == 3) ||
          (item.fieldName == 'money' && this.type == 5)) {
              fieldRules[temp.field] = [{
                required: true,
                message: this.$t('oa.examine.b0ec8db21a31ae1bf8a87d2e37454347'),
                trigger: ['blur', 'change']
              }]
            }
          }

          // disabled
          if (
          // 出差审批 差旅报销
            (item.fieldName == 'duration' && this.type == 3) ||
          (item.fieldName == 'money' && this.type == 5)
          ) {
            temp.disabled = true
          }

          // 特殊字段允许多选
          this.getItemRadio(item, temp)

          // 获取默认值
          if (item.formType == 'examine_cause' ||
          item.formType == 'business_cause') {
            if (this.action.type == 'update') {
              const itemValue = item.value || []
              const list = itemValue.map(element => {
                if (element.img) {
                  element.imgList = objDeepCopy(element.img || [])
                } else {
                  element.imgList = []
                }
                return element
              })
              fieldForm[temp.field] = { list: list } // 编辑的值 在value字段
            } else {
              fieldForm[temp.field] = {} // 加入默认值 可能编辑的时候需要调整
            }
          } else {
            if (temp.show) {
              // 经办人自动填充为当前用户
              if (item.fieldName == 'handled') {
                item.defaultValue = [this.userInfo]
                if (this.action.type == 'update') {
                  if (isObject(temp.value)) {
                    item.value = [temp.value.userId]
                  } else if (isArray(temp.value)) {
                    item.value = temp.value.map(item => item.userId)
                  }
                }
              }
              if (item.fieldName == 'submitDeptId') {
                item.defaultValue = [this.userInfo]
              }
              if (item.fieldName == 'telephone') {
                item.defaultValue = this.userInfo.mobile
                if (this.action.type == 'update') {
                  item.value = temp.value
                }
              }
              if (item.fieldName == 'submitTime') {
                item.defaultValue = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
                if (this.action.type == 'update') {
                  item.value = temp.value
                }
              }
              fieldForm[temp.field] = this.getItemValue(item, this.action.data, this.action.type)
            }
          }
          fields.push(temp)
          baseFields.push(item)
        })
        fieldList.push(fields)
      })
      this.baseFields = baseFields
      this.fieldList = fieldList

      // fieldRules 额外的自定义规则
      this.fieldRules = fieldRules
      const result = this.getFormContentByOptionsChange(fieldList, fieldForm)
      this.fieldForm = result.fieldForm
      this.fieldRules = result.fieldRules
    },

    /**
     * @description: 保存数据
     * @param {*} type
     * @return {*}
     */
    saveClick(type) {
      this.loading = true
      const crmForm = this.$refs.crmForm
      crmForm.validate(valid => {
        if (valid) {
          // 如果 afNewApply 说明没有开始审批流
          const wkFlowResult = this.$refs.afNewApply ? this.$refs.afNewApply.getParams() : {
            pass: true,
            flowParams: { list: [] }
          }
          if (wkFlowResult.pass) {
            const params = {
              oaExamine: { categoryId: this.categoryId },
              oaExamineRelation: {},
              field: [],
              oaExamineTravelList: []
            }
            this.getSubmiteParams([].concat.apply([], this.fieldList), params)
            // 审批流
            const dataMap = this.getWkFlowDataMap(this.fieldForm, wkFlowResult.flowParams.paramsData?.userFieldNames)
            params.examineFlowData = {
              label: this.examineAdvancedSetting.label,
              dataMap,
              flowDataList: wkFlowResult.flowParams.list
            }
            this.submiteParams(params, type)
          } else {
            this.loading = false
            this.$message.error(this.$t('oa.examine.24d4a8f0f309106b0aacfb352d86b9a3'))
          }
        } else {
          this.loading = false
          // 提示第一个error
          this.getFormErrorMessage(crmForm)
          return false
        }
      })
    },

    /**
     * @description: 自定义参数
     * @return {*}
     */
    getCustomFieldPostParams() {
      return new Promise((resolve, reject) => {
        const crmForm = this.$refs.crmForm
        crmForm.validate(valid => {
          if (valid) {
            const params = {
              oaExamine: { categoryId: this.categoryId },
              oaExamineRelation: {},
              field: [],
              oaExamineTravelList: []
            }
            this.getSubmiteParams([].concat.apply([], this.fieldList), params)
            // 将系统明细信息 交于 fileName cause，方便审批页面取值
            params.oaExamine.cause = params.oaExamineTravelList
            resolve({
              entity: params.oaExamine,
              field: params.field
            })
          } else {
            this.loading = false
            // 提示第一个error
            this.getFormErrorMessage(crmForm)
            reject()
            return false
          }
        })
      })
    },

    /**
     * 上传
     */
    submiteParams(params, type) {
      // eslint-disable-next-line
      for (const key in this.relatedBusinessInfo) {
        const list = this.relatedBusinessInfo[key]
        params.oaExamineRelation[key + 'Ids'] = list
          .map(function(item, index, array) {
            return item[key + 'Id']
          })
          .join(',')
      }

      params.oaExamine['batchId'] = this.batchId

      if (this.action.type == 'update') {
        params.oaExamine.examineId = this.action.id
      }
      const request = type == 'save' ? oaExamineSaveAndUpdateAPI : oaExamineSaveDraftAPI
      request(params)
        .then(res => {
          this.loading = false
          this.hidenView()
          this.$message.success(this.$t('oa.examine.e780521e1280c03100c7bfb48e64c661'))
          this.$store.dispatch('GetBacklogNum')
          // 回到保存成功
          this.$emit('save-success', type)
        })
        .catch(() => {
          this.loading = false
        })
    },

    /**
     * 拼接上传传输
     */
    getSubmiteParams(array, params) {
      for (let index = 0; index < array.length; index++) {
        const element = array[index]
        const dataValue = this.fieldForm[element.fieldName]
        if (element.fieldName == 'cause') {
          if (element.formType == 'business_cause') {
            params.oaExamineTravelList = dataValue.list
          } else if (element.formType == 'examine_cause') {
            for (let index = 0; index < dataValue.list.length; index++) {
              const cause = dataValue.list[index]
              var causeCopy = Object.assign({}, cause)
              delete causeCopy['imgList']
              params.oaExamineTravelList.push(causeCopy)
            }
          }
        } else {
          if (element.fieldType == 1) {
            params.oaExamine[element.fieldName] = this.getRealParams(element, dataValue)
          } else if (element.formType !== 'desc_text') { //  描述文字忽略
            params.field.push({
              fieldName: element.fieldName,
              fieldType: element.fieldType,
              name: element.name,
              type: element.type,
              fieldId: element.fieldId,
              value: this.getRealParams(element, dataValue)
            })
          }
        }
      }
      return params
    },

    /** 图片和附件 */

    /**
     * 上传图片
     */
    imgFileUploadSuccess(response, file, fileList) {
      this.imgFileList = fileList
    },

    /**
     * 查看图片
     */
    handleFilePreview(file) {
      if (file.response || file.fileId) {
        let perviewFile
        if (file.response) {
          perviewFile = file.response.data
        } else {
          perviewFile = file
        }
        this.$wkPreviewFile.preview({
          index: 0,
          data: [perviewFile]
        })
      }
    },
    beforeRemove(file, fileList) {
      if (file.response || file.fileId) {
        let fileId
        if (file.response) {
          fileId = file.response.data.fileId
        } else {
          fileId = file.fileId
        }
        this.$confirm(
          this.$t('oa.examine.2efddb49abac916a3883d9643c31be33'),
          this.$t('oa.examine.4a1ebc3388a0e99e8619bc7a9cd44711'),
          {
            confirmButtonText: this.$t('oa.examine.0610ea55290929f04b95d5d044ae913c'),
            cancelButtonText: this.$t('oa.examine.586fd397be980c7a1bf51039acc4ffe1'),
            type: 'warning'
          }
        )
          .then(() => {
            crmFileDeleteAPI({
              id: fileId
            })
              .then(res => {
                this.$message.success(this.$t('oa.examine.20c1c406face419acd920f6c6e1f9acb'))
                var removeIndex = this.getFileIndex(
                  this.$refs.imageUpload.uploadFiles,
                  fileId
                )
                if (removeIndex != -1) {
                  this.$refs.imageUpload.uploadFiles.splice(removeIndex, 1)
                }
                removeIndex = this.getFileIndex(this.imgFileList, fileId)
                if (removeIndex != -1) {
                  this.imgFileList.splice(removeIndex, 1)
                }
              })
              .catch(() => {})
          })
          .catch(() => {})
        return false
      } else {
        return true
      }
    },

    /**
     * 附件索引
     */
    getFileIndex(files, fileId) {
      var removeIndex = -1
      for (let index = 0; index < files.length; index++) {
        const item = files[index]
        let itemFileId
        if (item.response) {
          itemFileId = item.response.data.fileId
        } else {
          itemFileId = item.fileId
        }
        if (itemFileId == fileId) {
          removeIndex = index
          break
        }
      }
      return removeIndex
    },
    fileUploadSuccess(response, file, fileList) {
      this.fileList = fileList
    },
    handleFileRemove(file, fileList) {
      if (file.response || file.fileId) {
        let fileId
        if (file.response) {
          fileId = file.response.data.fileId
        } else {
          fileId = file.fileId
        }
        this.$confirm(
          this.$t('oa.examine.075cbf7cd1ff519e07e27cebd14fab60'),
          this.$t('oa.examine.96fbc75b247880e95ce639f3c11592cf'),
          {
            confirmButtonText: this.$t('oa.examine.f1aa9295256c9cf5052560ba2c318d13'),
            cancelButtonText: this.$t('oa.examine.906004bc408b68d90557d2de1d93d3cf'),
            type: 'warning'
          }
        )
          .then(() => {
            crmFileDeleteAPI({
              id: fileId
            })
              .then(res => {
                this.$message.success(this.$t('oa.examine.e31e765b1935c72a3224b87f837ef95c'))
                var removeIndex = this.getFileIndex(
                  this.$refs.fileUpload.uploadFiles,
                  fileId
                )
                if (removeIndex != -1) {
                  this.$refs.fileUpload.uploadFiles.splice(removeIndex, 1)
                }
                removeIndex = this.getFileIndex(this.fileList, fileId)
                if (removeIndex != -1) {
                  this.fileList.splice(removeIndex, 1)
                }
              })
              .catch(() => {})
          })
          .catch(() => {})
        return false
      } else {
        return true
      }
    },
    /**
     * 附件
     */
    httpRequest(val) {
      this.$wkUploadFile.upload({
        file: val.file,
        params: {
          batchId: this.batchId
        }
      }).then(({ res }) => {
        const data = res.data || {}
        const list = this.fileList || []
        list.push(data)
        this.$set(this.fileList, 'files', list)
        this.$message.success(this.$t('oa.examine.1aa068d8c02d50e2429d0b1338d7a742'))
      }).catch(() => {})
    },
    /**
     * 附件删除
     */
    fileDelete(index, item, field) {
      this.fileList.splice(index, 1)
    },

    /**
     * @description: 添加经办人
     * @return {*}
     */
    addUser() {
      this.$refs.wkUserDialogSelect[0].visible = true
    },

    /**
     * @description: 经办人为空清空相关字段默认值
     * @param {*} data
     * @return {*}
     */
    userChange(data) {
      if (!data.length && this.action.type == 'save') {
        this.fieldForm.telephone = ''
        this.fieldForm.submitDeptId = []
      }
    },

    /**
     * 关闭
     */
    hidenView() {
      this.$emit('hiden-view')
    },

    /**
     * 根据类型获取标题展示名称
     */
    getTitle() {
      return this.action.type == 'update'
        ? this.$t('oa.examine.85cab870a3ac852306c406a7104f0b93') + this.categoryTitle
        : this.$t('oa.examine.f2ab5cafd11ab7e0862d881c4eb9ecb7') + this.categoryTitle
    }
  }
}
</script>

<style lang="scss" scoped>
.crm-create-container {
  position: relative;
  height: 100%;
}

.crm-create-header {
  flex-shrink: 0;
  height: 40px;
  padding: 0 10px;
  margin-bottom: 20px;

  .close {
    display: block;
    padding: 10px;
    margin-right: -10px;
    font-size: 24px;
    color: #909399;
    cursor: pointer;
  }

  .close:hover {
    color: $--color-primary;
  }
}

.crm-create-body {
  flex: 1;
  overflow-x: hidden;
  overflow-y: auto;
}

/** 将其改变为flex布局 */
.crm-create-box {
  display: flex;
  flex-wrap: wrap;
  padding: 0 10px 15px;
}

.crm-create-item {
  flex: 0 0 50%;
  flex-shrink: 0;

  // overflow: hidden;
  padding-bottom: 10px;
}

// 图片 附件
.img-accessory {
  padding: 0 12px 0 20px;
  margin-bottom: 5px;
  margin-bottom: 10px;
  font-size: 12px;

  img {
    width: 16px;
    vertical-align: middle;
  }

  .img-box ::v-deep .el-upload {
    width: 80px;
    height: 80px;
    line-height: 90px;
  }

  .img-box ::v-deep .el-upload-list {
    .el-upload-list__item {
      width: 80px;
      height: 80px;

      img {
        object-fit: contain;
        vertical-align: top;
      }
    }
  }

  .img-box {
    position: relative;
    margin-top: 40px;

    .add-img {
      position: absolute;
      top: -32px;
      left: 0;
      padding-left: 0;
    }
  }

  .add-accessory {
    margin-top: 25px;
    margin-bottom: 20px;
    color: #2362fb;

    .wukong-file {
      font-size: 13px;
    }
  }
}

.related-business {
  padding: 0 20px;
}

.wk-form {
  ::v-deep .el-form-item {
    &.is-business_cause,
    &.is-examine_cause {
      flex: 0 0 100%;
      width: 0;
    }
  }
}

.upload-file ::v-deep .el-upload-list--picture {
  display: none;
}

// 添加btn
.add-btn {
  display: inline-block;
  min-width: 92px;
  padding: 3px 10px;
  margin-top: 8px;
  font-size: 12px;
  color: $--color-text-primary;
  text-align: center;
  cursor: pointer;
  background-color: $--button-default-background-color;
  border-radius: $--border-radius-base;

  .wk-l-plus {
    font-size: 12px;
  }
}

.add-btn:hover {
  background-color: $--button-hover-background-color;
}

.sub-task-all {
  border: 1px solid $--color-n30;
  border-bottom: none;
  border-radius: 4px;
  box-shadow: $--box-shadow-bottom;
}
</style>
